
//
// Copyright 2009 Arne Halvorsen (arne.halvorsen@gmail.com)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

// Project page: http://code.google.com/p/mf4j/

//
// 091116 - aha42 - Starts in line change tracking.
// 091121 - aha42 - Added project page link (google code) to header comment.
// 091210 - aha42 - IOException -> FlickrException.
//

package org.aha.mf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * <p>
 *   {@link Authenticator} that simply writes login URL to
 *   {@link System#out standard out} and expect end user to copy and past to
 *   browser.
 * </p>
 * @author Arne Halvorsen (aha42)
 */
public final class SimpleAuthenticator implements Authenticator 
{
  /**
   * <p>
   *   Single shared instance.
   * </p>
   */
  public static SimpleAuthenticator INSTANCE=new SimpleAuthenticator();
  
  // Singleton pattern dictates private constructor.
  private SimpleAuthenticator(){} 

  // Specified in Authenticator.
  public boolean authenticate(FlickrSession fs, String perms) 
    throws FlickrException 
  {
    if (perms==null)
    {
      throw new NullPointerException("perms");
    }
    
    String lurl=fs.getLoginUrlSpec(perms);

    System.out.println("Go to the page the URL below points to and "+
      "authenticate this application or type 'q' or 'quit' to abbort.");
    System.out.println();
    System.out.println(lurl);
    
    try
    {
      BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
      String line=br.readLine();
      line=(line==null) ? "" : line.trim();
      if (line.equalsIgnoreCase("q") || line.equalsIgnoreCase("quit"))
        return false;
    }
    catch (IOException iox)
    {
      throw new FlickrException(iox);
    }
    
    return true;
  }
  
}
